//
//  XS_NetWork.swift
//  Pods
//
//  Created by 韩云智 on 2020/7/15.
//
//  网络请求框架

import Foundation
import RxAlamofire
import RxSwift
import HandyJSON
import Alamofire

// 接口返回数据模型
open class XS_Response: XS_BaseModel {
    open var success: Bool = false
    open var code: String = ""
    open var data: Any?
    open var msg: String = ""
    
    open func dataToModel<T:HandyJSON>(_ modelType:T.Type) -> T {
        guard let data = data as? [String:Any] else {
            return T.init()
        }
        return JsonUtil.dictionaryToModel(data, T.self)
    }
    open func dataToArray<T:HandyJSON>(_ modelType:T.Type) -> [T] {
        guard let data = data as? [[String:Any]] else {
            return []
        }
        return JsonUtil.arrayToModel(data, T.self)
    }
}

public extension String {
    /// 拼接域名地址
    func spliceApi() -> String {
        spliceApiString(XS_NetWork.api)
    }
    func spliceH5Api() -> String {
        spliceApiString(XS_NetWork.api_h5)
    }
    func spliceApiString(_ api: String) -> String {
        let str = addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? self
        if hasPrefix("https://") || hasPrefix("http://") {
            return str
        }
        if hasPrefix("/") {
            return api + str
        }
        return api + "/" + str
    }
}

open class XS_NetWork {
    /// 接口域名/IP前缀
//    public static var api = "http://xdapi.yaoxuedao.com.cn/api"  // 线上
    public static var api = "http://xdapi.yaoxuedao.com.cn/testapi"  // 测试
//    public static var api = "http://192.168.1.37:9876"  // 本地测试
    
    public static var api_h5 = "http://xdapi.yaoxuedao.com.cn"
    
    public static var getParamBlock: (([String: Any]?)->[String: Any]?) = { $0 }
    public static var getHeadersBlock: (([String: String])->[String: String]) = { $0 }
    public static var filterState = { (resp: XS_Response) -> Bool in
        switch resp.code {
//        case 400:
//            hideActivity()
//            return false
        default:
            return true
        }
    }
    
    /// 发起json格式的post请求
    /// - Parameter urlStr: 请求链接字符串
    public static func xs_requestJson(_ urlStr: String, method: Alamofire.HTTPMethod = .post, parameters: [String: Any]? = nil, headers: [String : String] = [:]/*, toLogin: Bool = false*/) -> Observable<Any> {
        
        let headers = getHeadersBlock(headers)
        let parameters = getParamBlock(parameters)
        
        let urlStr = urlStr.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? urlStr
        return json(method, urlStr.spliceApi(), parameters: parameters, encoding: JSONEncoding.default, headers: HTTPHeaders(headers))
            .observe(on: MainScheduler.instance)
            .filter { _ in
                print("------------------")
                print(urlStr.spliceApi())
                print(parameters ?? [:])
                print("------------------")
                return true
            }
    }
    public static func requestJson(_ urlStr: String, method: Alamofire.HTTPMethod = .post, parameters: [String: Any]? = ["":""], headers: [String : String] = [:]/*, toLogin: Bool = false*/) -> Observable<XS_Response> {
        let observable = xs_requestJson(urlStr, method: method, parameters: parameters, headers: headers)
            .mapResponse(type: XS_Response.self)
            .filter(filterState)
        #if DEBUG
        return observable.debug()
        #else
        return observable
        #endif
    }
    
    /// data / fileUrl 二选一， 传fileUrl时 必须传 mimeType
    struct XS_UploadM {
        let data: Data?
        let fileUrl: URL?
        let name: String
        let fileName: String?
        let mimeType: String?
        
        init(_ name: String = "file", data: Data? = nil, fileUrl: URL? = nil, fileName: String? = nil, mimeType: String? = nil) {
            self.data = data
            self.fileUrl = fileUrl
            self.name = name
            self.fileName = fileName ?? name
            self.mimeType = mimeType
        }
    }
    struct XS_UploadImgResponse: Decodable {
        let success: Bool
        let code: String
        let msg: String
        let data: String
    }
    
    static func xs_uploadFile(_ model: XS_UploadM, completionHandler: ((XS_UploadImgResponse?) -> Void)? = nil) {
        xs_uploadFiles([model], completionHandler: completionHandler)
    }
    
    
    static func xs_uploadFiles(_ models: [XS_UploadM], completionHandler: ((XS_UploadImgResponse?) -> Void)? = nil) {
        let headers = getHeadersBlock([:])
        AF.upload(multipartFormData: { multipartFormData in
            for model in models {
                if let data = model.data {
                    multipartFormData.append(data, withName: model.name, fileName: model.fileName, mimeType: model.mimeType)
                } else if let url = model.fileUrl, let mimeType = model.mimeType {
                    multipartFormData.append(url, withName: model.name, fileName: model.fileName ?? "", mimeType: mimeType)
                }
            }
        }, to: "/file/upload".spliceApi(), headers: HTTPHeaders(headers))
        .responseDecodable(of: XS_UploadImgResponse.self) { completionHandler?($0.value) }
    }
}
